package com.zadtek.shopmall.activities;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.goyourfly.multi_picture.ImageLoader;
import com.goyourfly.multi_picture.MultiPictureView;
import com.iarcuschin.simpleratingbar.SimpleRatingBar;
import com.zadtek.shopmall.R;
import com.zadtek.shopmall.base.AbsActivity;
import com.zadtek.shopmall.bean.EvaluateProductBean;
import com.zadtek.shopmall.bean.OperateResponseBean3;
import com.zadtek.shopmall.bean.UpLoadImgResponse;
import com.zadtek.shopmall.net.BaseObserver;
import com.zadtek.shopmall.net.BaseResponse;
import com.zadtek.shopmall.net.NetTool;
import com.zadtek.shopmall.utils.LogUtil;
import com.zadtek.shopmall.utils.ToastUtil;
import com.zadtek.shopmall.view.GridSpacingItemDecoration;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.nereo.multi_image_selector.MultiImageSelector;

public class EvaluateOrderActivity extends AbsActivity implements View.OnClickListener {
    private ImageView ivProductImg;
    private TextView tvProductTitle;
    private TextView tvProductPrice;
    private SimpleRatingBar rbMark;
    private TextView tvReasonDesc;
    private EditText etEvaluateDesc;
    private MultiPictureView multipleImage;
    private TextView tvBtnApply;
    private ImageView ivBack;
    private TextView title;
    private RecyclerView picContainer;
    private EvaluateProductBean productBean;
    private ArrayList<String> path = new ArrayList<>();
    private ArrayList<String> pathCopy = new ArrayList<>();
    private SelectAdapter selectAdpter;
    private int maxChoose = 4;

    private void initView() {
        ivBack = (ImageView)findViewById(R.id.ic_back);
        ivBack.setVisibility(View.VISIBLE);
        title = (TextView)findViewById(R.id.title);
        title.setText("评价");
        ivProductImg = (ImageView)findViewById( R.id.iv_product_img );
        tvProductTitle = (TextView)findViewById( R.id.tv_product_title );
        tvProductPrice = (TextView)findViewById( R.id.tv_product_price );
        rbMark = (SimpleRatingBar)findViewById( R.id.rb_mark );
        tvReasonDesc = (TextView)findViewById( R.id.tv_evaluate_desc );
        etEvaluateDesc = (EditText)findViewById( R.id.et_evaluate_desc );
        multipleImage = (MultiPictureView)findViewById( R.id.multiple_image );
        tvBtnApply = (TextView)findViewById( R.id.tv_btn_apply );
        picContainer = findViewById(R.id.pic_container);
    }

    @Override
    public int setView() {
        return R.layout.activity_evaluate_order;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        productBean = (EvaluateProductBean) getIntent().getSerializableExtra("data");
        if(productBean == null){
            ToastUtil.showToast("没有数据传过来！");
        }
        initView();
        initLogic();
        updateView();
    }

    private void updateView() {
        tvProductTitle.setText(productBean.getGoods_name());
        tvProductPrice.setText(productBean.getGoods_price());
        Glide.with(mActivity).load(productBean.getGoods_img()).placeholder(R.drawable.placeholder).into(ivProductImg);
    }
    RequestListener mRequestListener = new RequestListener() {
        @Override
        public boolean onException(Exception e, Object model, Target target, boolean isFirstResource) {
            return false;
        }

        @Override
        public boolean onResourceReady(Object resource, Object model, Target target, boolean isFromMemoryCache, boolean isFirstResource) {
            return false;
        }

    };
    private void initLogic() {
        MultiPictureView.setImageLoader(new ImageLoader() {
            @Override
            public void loadImage(@NotNull ImageView image, @NotNull Uri uri) {
                String path = uri.getPath();
                path = path.substring(1);
                LogUtil.d(path);
                Glide.with(EvaluateOrderActivity.this)
                        .load(path)
                        .into(image);
            }
        });
        selectAdpter = new SelectAdapter(R.layout.list_item_image,pathCopy);
        selectAdpter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if(view.getId() == R.id.delete){
                    path.remove(position);
                    shouldDrawAdd();
                }
            }
        });
        selectAdpter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if(pathCopy.get(position).equals("")){
                    performCodeWithPermission("需要相机权限", new PermissionCallback() {
                        @Override
                        public void hasPermission() {
                            MultiImageSelector.create().showCamera(true).multi().count(maxChoose-path.size()).start(EvaluateOrderActivity.this,200);
                        }

                        @Override
                        public void noPermission() {

                        }
                    }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
            }
        });
        picContainer.setLayoutManager(new GridLayoutManager(this,3));
        picContainer.addItemDecoration(new GridSpacingItemDecoration(3,getResources().getDimensionPixelSize(R.dimen.little_margin), true));
        picContainer.setAdapter(selectAdpter);
        picContainer.setHasFixedSize(true);
        shouldDrawAdd();
        ivBack.setOnClickListener(this);
        tvBtnApply.setOnClickListener(this);
        multipleImage.setAddClickCallback(new MultiPictureView.AddClickCallback() {
            @Override
            public void onAddClick(View view) {
                performCodeWithPermission("需要相机权限", new PermissionCallback() {
                    @Override
                    public void hasPermission() {
                        MultiImageSelector.create().showCamera(true).multi().count(4-path.size()).start(EvaluateOrderActivity.this,200);
                    }

                    @Override
                    public void noPermission() {

                    }
                }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
        });
        multipleImage.setDeleteClickCallback(new MultiPictureView.DeleteClickCallback() {
            @Override
            public void onDeleted(@NotNull View view, int index) {
                path.remove(index);
            }
        });
        rbMark.setOnRatingBarChangeListener(new SimpleRatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(SimpleRatingBar simpleRatingBar, float rating, boolean fromUser) {
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == 200){
            ArrayList<String> list = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
            NetTool.uploadFile(list).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<BaseResponse<UpLoadImgResponse>>(this) {
                        @Override
                        public void onData(BaseResponse<UpLoadImgResponse> value) {
                            if(value.getCode() == 0 && value.getData()!=null){
                                if(value.getData().getImage().size()!=0){
                                    path.addAll(value.getData().getImage());
                                    //updateMV();
                                    shouldDrawAdd();
                                }
                            }
                        }
                    });
        }
    }

    private void updateMV() {
        //todo 图片不显示
        List<Uri> uris = new LinkedList<>();
        for(String pat:path){
            Uri uri = new Uri.Builder().appendPath(pat).build();
            uris.add(uri);
        }
        multipleImage.setList(uris);
    }

    private String getImgs() {
        String imgs = "";
        for(String pat:path){
            imgs= imgs+pat+"@";
        }
        return imgs;
    }

    private void shouldDrawAdd(){
        if(path.size()<maxChoose){
            pathCopy.clear();
            pathCopy.addAll(path);
            pathCopy.add("");
        }else{
            pathCopy.clear();
            pathCopy.addAll(path);
        }
        selectAdpter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ic_back:
                finish();
                break;
            case R.id.tv_btn_apply:
                submit();
                break;
        }
    }

    private void submit() {
        String content = etEvaluateDesc.getText().toString();
        if(TextUtils.isEmpty(content)){
            ToastUtil.showToast("请说点什么吧！");
            return;
        }
        Map<String, Object> param = NetTool.newParams();
        param.put("starnum",rbMark.getNumberOfStars());
        param.put("goods_id",productBean.getGoods_id());
        //param.put("user_name", UserInfoManger.);
        param.put("shop_id",productBean.getRu_id());
        param.put("order_id",productBean.getOrder_id());
        param.put("rec_id",productBean.getRec_id());
        param.put("content",content);
        param.put("image",getImgs());
        NetTool.getApi().evaluate(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<OperateResponseBean3>>(this) {
                    @Override
                    public void onData(BaseResponse<OperateResponseBean3> value) {
                        if(value.getCode() == 0 && value.getData()!=null){
                            if(value.getData().isSuccess()){
                                ToastUtil.showToast("评价成功！");
                                finish();
                            }else {
                                ToastUtil.showToast("提交失败！");
                            }
                        }
                    }
                });
    }

    public class SelectAdapter extends BaseQuickAdapter<String,BaseViewHolder> {
        public SelectAdapter(int layoutResId, @Nullable List<String> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            helper.addOnClickListener(R.id.delete);
            if(item.equals("")){
                Glide.with(EvaluateOrderActivity.this).load(R.drawable.ic_add).into((ImageView) helper.getView(R.id.iv_img));
                helper.setVisible(R.id.delete,false);
            }else{
                helper.setVisible(R.id.delete,true);
                Glide.with(EvaluateOrderActivity.this).load(item).into((ImageView) helper.getView(R.id.iv_img));
            }
        }
    }
}
